package cn.bellychang.deferredresult;

import cn.bellychang.model.Order;
import cn.bellychang.response.ErrorCode;
import cn.bellychang.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author ChangLiang
 * @date 2020/9/23
 */
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        // 无限循环
        // 如果不单开线程 会阻塞整个系统的启动
        // 这里模拟应用1的线程2来监听消息队列的处理结果
        new Thread(()->{
            while (true) {
                Response response = new Response();
                ErrorCode errorCode = ErrorCode.OK;
                Long id = null;
                try {
                    Order order = (Order) mockQueue.getQueue().take();
                    id = order.getId();
                    logger.info("返回订单处理结果 order:{}", order);
                    response.setData(order);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
                if (Optional.ofNullable(id).isPresent()) {
                    response.setErrorCode(errorCode.code);
                    response.setValue(errorCode.value);
                    deferredResultHolder.getMap().get(id).setResult(response);
                }
            }
        },"application1: queue-listener-thread").start();
    }
}
